package com.jokerku.mini.schedule.task;

import com.jokerku.mini.schedule.common.Constants;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: guzq
 * @CreateTime: 2023/05/25 11:22
 * @Description: 定时任务注册
 * @Version: 1.0
 */
@Component("mini-schedule-cron-task-register")
public class CronTaskRegister implements DisposableBean {

    @Resource(name = "mini-schedule-task-scheduler")
    private TaskScheduler taskScheduler;

    public void addCornTask(ScheduleRunnable runnable, String cronExpression) {
        if (Constants.SCHEDULED_TASK_MAP.containsKey(runnable.getTaskId())) {
            removeCronTask(runnable);
        }
        // 执行定时任务
        CronTask cronTask = new CronTask(runnable, cronExpression);
        ScheduledTask scheduledTask = scheduleCronTask(cronTask);
        Constants.SCHEDULED_TASK_MAP.put(runnable.getTaskId(), scheduledTask);
    }

    public void removeCronTask(ScheduleRunnable runnable) {
        ScheduledTask task = Constants.SCHEDULED_TASK_MAP.remove(runnable.getTaskId());
        if (null != task) {
            task.cancel();
        }
    }

    /**
     * 执行定时任务
     *
     * @param cronTask
     * @return
     */
    private ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }

    @Override
    public void destroy() {
        for (ScheduledTask scheduledTask : Constants.SCHEDULED_TASK_MAP.values()) {
            scheduledTask.cancel();
        }

        Constants.SCHEDULED_TASK_MAP.clear();
    }
}
